<?php
/*
 * Copyright (c) 2013 Eugene Kuzmenko
 *
 * Permission  is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in  the Software without restriction, including without limitation the rights
 * to  use,  copy,  modify,  merge, publish, distribute, sublicense, and/or sell
 * copies  of  the  Software,  and  to  permit  persons  to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The  above  copyright  notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE  SOFTWARE  IS  PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED,  INCLUDING  BUT  NOT  LIMITED  TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS  FOR  A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS  OR  COPYRIGHT  HOLDERS  BE  LIABLE  FOR  ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 * For more information, see <http://www.aljey.com>.
 */

use Al\Core\Lib\Service;

/**
 * This is a front controller, all requests to non-static file urls should be
 * directed though here.
 * If you are using apache and have an access to your virtual host configuration
 * please refrain from creating an .htaccess file.
 * Instead put the following in your virtual host configuration:
 * <Directory "<web root>"> // the absolute path to the "web" directory
 *   RewriteEngine On
 *   RewriteCond %{REQUEST_FILENAME} -s [OR]
 *   RewriteCond %{REQUEST_FILENAME} -l [OR]
 *   RewriteCond %{REQUEST_FILENAME} -d
 *   RewriteRule ^.*$ - [NC,L]
 *   RewriteRule ^.*$ <web root>/index.php [NC,L]
 *   AllowOverride None
 * </Directory>
 */
$lsp = strtolower($_SERVER['SERVER_PROTOCOL']);
$_SERVER['protocol'] = substr($lsp, 0, strpos($lsp, '/')) .
  ((!empty($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] == 'on')) ? 's' : '');
$_SERVER['uri'] = '/' . trim(parse_url(isset($_SERVER['REQUEST_URI']) ?
  $_SERVER['REQUEST_URI'] : $_SERVER['PHP_SELF'], PHP_URL_PATH), '/');
if ($_SERVER['unique'] = isset($_GET['__fmod'])) unset($_GET['__fmod']);
$_SERVER['address'] = "{$_SERVER['protocol']}://{$_SERVER['SERVER_NAME']}" .
  (($_SERVER['SERVER_PORT'] == '80') ? '' : ":{$_SERVER['SERVER_PORT']}");
$_SERVER['location'] = $_SERVER['address'] . $_SERVER['uri'] .
  ($_GET ? '?' . http_build_query($_GET) : '');
$mime = include 'mime.php';
if (is_file($file = 'cache/routes.php')) {
  $routes = (array)include $file;
  $request_id = md5($_SERVER['location']);
  if (isset($routes[$request_id])) {
    include 'download.php';
    download($routes[$request_id]['file'], $routes[$request_id]['type']);
  }
}
set_error_handler(function ($errno, $errstr, $errfile, $errline) {
  if ('0' !== ini_get('error_reporting')) {
    throw new \ErrorException($errstr, 0, $errno, $errfile, $errline);
  }
}, E_ALL);
define('ROOT_DIR', __DIR__);
include '../src/Al/Core/Lib/ParameterHolder.php';
include '../src/Al/Core/Lib/Service.php';
include '../src/Al/Core/Lib/Config.php';
include '../src/Al/Core/Lib/YAML.php';
include '../src/Al/Core/Lib/Autoload.php';
Service::set(array(
  'autoload' => function () { return new \Al\Core\Lib\Autoload; },
  'yaml' => function () { return new \Al\Core\Lib\YAML; },
  'config' => function () { return new \Al\Core\Lib\Config; },
  'cache' => function ($service) {
    foreach (array(
        array('apcu', 'APCu', function () { return extension_loaded('apcu'); }),
        array('apc', 'APC', function () { return extension_loaded('apc'); }),
        array('xcache', 'XCache', function () use (&$service) {
          $config = $service['config'];
          return extension_loaded('xcache') &&
            !ini_get('xcache.admin.enable_auth') && ($config->human2byte(
              ini_get('xcache.var_size')) >= $config->human2byte('128M'));
        }),
        array('memcache', 'Memcache', function () {
          return extension_loaded('memcache'); }),
        array('redis', 'Redis', function () {
          return extension_loaded('redis'); }),
        array('file', 'FileCache', function () { return true; }),
    ) as $cache) {
      $available = $cache[2]();
      if ($available) {
        $class = "Al\\Core\\Lib\\CacheDriver\\{$cache[1]}";
        return new $class;
      }
    }
  },
));
Service::get('autoload')->register();
Service::get('cache');
Service::get('config')->bootstrap();
Service::get('request')->route();